import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Config } from './config.interface';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'my-auth-token'
    })
};
@Injectable()
export class HttpService {
    basicUrl = 'http://192.168.3.253/';
    constructor(private http: HttpClient) { }

    configUrl = 'assets/config.json';
    post(url, param): Observable<any> {
        return this.http.post(this.basicUrl+url, param, httpOptions).pipe(
            retry(1),
            catchError(this.handleError)
        )
    }
    getConfig(): Observable<HttpResponse<Config>> {
        return this.http.get<Config>(this.configUrl, { observe: 'response' }).pipe(
            retry(3),
            catchError(this.handleError)
        );;
    }
    private handleError(error: any) {
        if (error.error instanceof ErrorEvent) {
            // 发生客户端或网络错误。相应处理。
            console.error('An error occurred:', error.error.message);
        } else {
            // 后端返回一个不成功的响应代码。
            // 反应体可能包含出问题的线索
            console.error(
                `Backend returned code ${error.status}, ` +
                `body was: ${error.error}`);
            const msg = '请求失败';
            if (+error.status === 400) {
                console.error(msg);
            }
            if (+error.status === 404) {
                console.error('请检查路径是否正确');
            }
            if (+error.status === 500) {
                console.error('请求的服务器错误');
            }

        }
        // 返回带有用户面临错误消息的可观察数据
        return throwError(
            'Something bad happened; please try again later.');
    };
}